<?php

class Application_Model_Mapper
{
    /**
     * @var Zend_Db_Table_Abstract|Application_Model_DbTable_Interface
     */
    protected $table;
//    protected $db;
    /**
     * @var Application_Model_ModelAbstract
     */
    protected $model;

    const DEFAULT_LIMIT = 10;

    /**
     * @param Zend_Db_Table_Abstract          $table
     * @param Application_Model_ModelAbstract $model
     * @param null                            $options
     */
    public function __construct(Zend_Db_Table_Abstract $table, Application_Model_ModelAbstract $model, $options = null)
    {
        $this->table = $table;

        if (!$this->getTable() instanceof Zend_Db_Table_Abstract) {
            throw new ErrorException('Not Valid Type Table. Not Found class ' . $this->getTable());
        }

        $this->model = $model;

        if ($options) {
            foreach ($options as $property => $value) {
                $model->$property = $value;
            }
        }
    }

    /**
     * @param null|Zend_Db_Table_Select $select
     * @return array
     */
    public function fetchAll($select = null)
    {
        $rows = $this->getTable()->fetchAll($select);
        $models = array();

        if ($rows) {
            $rows->toArray();

            foreach ($rows as $row) {
                $model = clone $this->model;
                $model->setOptions($row);
                $models[] = $model;
            }

        }

        return $models;
    }

    public function getById($id)
    {
        $row = $this->getTable()->find($id);

        if ($row && $row->toArray()) {
            $row->toArray();
            $model = clone $this->model;
            $row = reset($row);
            $model->setOptions(reset($row));
            return $model;
        } else {
            return null;
        }
    }

    /**
     * @param array $where - поле => значение
     * @param string $order
     * @param array $limit - 'start' => с какого элемента начинать, 'count' => количество элементов
     *
     * @return Application_Model_ModelAbstract[]
     */
    public function getCollection($where = array(), $order = '', $limit = array())
    {
        $select = $this->getTable()->select();

        if ($where) {
            if (is_array($where)) {
                foreach ($where as $field => $value) {
                    if (is_int($field)) {
                        $select->where($value);
                    } else {
                        $select->where($field . ' = ?', $value);
                    }
                }
            } else {
                $select->where($where);
            }

        }

        if ($order) {
            $select->order($order);
        }

        if ($limit) {
            $select->limit($limit['count'], $limit['start']);
        }

        return $this->fetchAll($select);
    }

    /**
     * @param array $data - ключ массива  - поле в таблице, в которое нужно записать значение
     */
    public function insert($data = null)
    {
        if (is_array($data)) {
            return $this->getTable()->insert($data);
        } elseif ($data instanceof Application_Model_ModelAbstract) {
            //если передали объект
        } elseif ($data === null) {

        }

        return false;
    }

    /**
     * @param array $data
     * @param array $where
     * @return mixed
     */
    public function update($data, $where)
    {
        if ($data) {
            foreach ($data as $field => $value) {
                $data[$field] = $value;
            }

            return $this->getTable()->update($data, $where);
        } else {
//            $this->model;
//            return $this->getTable()->update($data, $where);
        }

        return false;
    }

    public function del($field, $id)
    {
        return $this->getTable()->fetchRow($this->getTable()->select()->where($field .' = ? ',$id))->delete();
    }

    public function getTable()
    {
        return $this->table;
    }

    public function getModel()
    {
        return $this->model;
    }

    public function save()
    {
        $row = $this->getModel()->toArray();

        if ($this->getModel()->getId()) {
            $this->update($row, $this->getTable()->getPrimaryKey(). '= '. $this->getModel()->getId());
        } else {
            $this->getTable()->insert($row);
        }

        return true;
    }

    public function getRentsByCategory(Application_Model_RentCategory $category)
    {
        if (!$category) {
            return array();
        }

        return $this->getCollection(array('rent_category' => $category->getId()), 'rent_priority ASC');
    }

    public function getRentCategoryBy4pu($category4pu)
    {
        if (!$category4pu) {
            return null;
        }

        $table = new Application_Model_DbTable_RentCategory();
        $row = $table->fetchRow($table->select()->where('category_4pu = (?)',  $category4pu));

        if (!$row) {
            return null;
        }

        return new Application_Model_RentCategory($row);
    }

    public static function getMailsStock()
    {
        $str = file_get_contents('log_stock_rent.txt');
        $rows = explode("\n", $str);
        return array_reverse($rows);
    }
}
